package com.project.app.utils.tools;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.hengyi.baseandroidcore.xutils.LogUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

public class BluetoothUtils {
    public UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private static BluetoothUtils instance = null;
    private BluetoothAdapter bluetoothAdapter = null;
    private boolean supportBluetooth = false;
    private static Context context;
    private List<BluetoothDevice> scanBluetooth = null;
    private CONNECION mType;
    private boolean listenerCallback;
    private BluetoothServerSocket bluetoothServerSocket;
    private boolean serverThreadSwitch;
    private boolean readThreadSwitch;
    private BluetoothUtils.ServerThread serverThread;
    private BluetoothSocket bluetoothSocket;
    private OutputStream blueOutputStream;
    private InputStream blueInputStream;
    private BluetoothUtils.BluetoothConnListener blueListener;
    private BluetoothUtils.ReadThread readThread;
    private BluetoothDevice clientBluetoothDevice;
    @SuppressLint({"HandlerLeak"})
    private Handler handler;

    public BluetoothUtils() {
        this.mType = BluetoothUtils.CONNECION.NONE;
        this.listenerCallback = true;
        this.serverThreadSwitch = false;
        this.readThreadSwitch = false;
        this.blueListener = null;
        this.handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        if (BluetoothUtils.this.blueListener != null) {
                            BluetoothUtils.this.blueListener.connSuccess();
                        }
                        break;
                    case 2:
                        if (BluetoothUtils.this.blueListener != null) {
                            BluetoothUtils.this.blueListener.connError(msg.obj.toString());
                        }
                        break;
                    case 4:
                        if (BluetoothUtils.this.blueListener != null) {
                            BluetoothUtils.this.blueListener.connClose(true, msg.obj.toString());
                        }
                        break;
                    case 5:
                        if (BluetoothUtils.this.blueListener != null) {
                            BluetoothUtils.this.blueListener.connClose(false, msg.obj.toString());
                        }
                        break;
                    case 200:
                        if (BluetoothUtils.this.blueListener != null) {
                            BluetoothUtils.this.blueListener.serverOpen();
                        }
                        break;
                    case 201:
                        if (BluetoothUtils.this.blueListener != null) {
                            BluetoothUtils.this.blueListener.connSuccess();
                        }
                        break;
                    case 203:
                        if (BluetoothUtils.this.blueListener != null) {
                            BluetoothUtils.this.blueListener.connError(msg.obj.toString());
                        }
                        break;
                    case 300:
                        if (BluetoothUtils.this.blueListener != null) {
                            BluetoothUtils.this.blueListener.onReceive(msg.getData().getByteArray("data"));
                        }
                    case 204:
                        if (BluetoothUtils.this.blueListener != null) {
                            BluetoothUtils.this.blueListener.serverClose();
                        }
                        break;
                    case 301:
                        if (BluetoothUtils.this.blueListener != null) {
                            BluetoothUtils.this.blueListener.onReceiveError(msg.obj.toString());
                        }
                }

            }
        };
    }

    public static synchronized BluetoothUtils getInstance(Context con) {
        Class var1 = BluetoothUtils.class;
        synchronized (BluetoothUtils.class) {
            context = con;
            if (instance == null) {
                instance = new BluetoothUtils();
            }

            return instance;
        }
    }

    public void init() {
        this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (this.bluetoothAdapter == null) {
            this.supportBluetooth = false;
        } else {
            this.supportBluetooth = true;
        }

    }

    public void init(String uuid) {
        this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (this.bluetoothAdapter == null) {
            this.supportBluetooth = false;
        } else {
            this.supportBluetooth = true;
        }

        this.MY_UUID = UUID.fromString(uuid);
    }

    public BluetoothUtils.CONNECION getmType() {
        return this.mType;
    }

    public boolean sendBluetoothMessage(byte[] buffer) {
        try {
            this.blueOutputStream.write(buffer);
            this.blueOutputStream.flush();
            return true;
        } catch (Exception var3) {
            return false;
        }
    }

    private void sendMessage(int what, Object obj, int arg1, int arg2) {
        if (this.listenerCallback) {
            Message msg = this.handler.obtainMessage();
            msg.what = what;
            msg.obj = obj;
            msg.arg1 = arg1;
            msg.arg2 = arg2;
            this.handler.sendMessage(msg);
        }

    }

    private void sendBundleMessage(int what, Object obj, Bundle bundle) {
        if (this.listenerCallback) {
            Message msg = this.handler.obtainMessage();
            msg.what = what;
            msg.obj = obj;
            msg.setData(bundle);
            this.handler.sendMessage(msg);
        }

    }

    public boolean isSupportBluetooth() {
        return this.supportBluetooth;
    }

    public void setBluetoothClientListener(BluetoothUtils.BluetoothConnListener bluetoothListener) {
        this.blueListener = bluetoothListener;
    }

    public BluetoothAdapter getBluetoothAdapter() {
        return this.bluetoothAdapter;
    }

    public boolean isEnabled() {
        return this.getBluetoothAdapter().isEnabled();
    }

    public String getAddress() {
        return this.getBluetoothAdapter().getAddress();
    }

    public String getName() {
        return this.getBluetoothAdapter().getName();
    }

    public boolean setName(String name) {
        return this.getBluetoothAdapter().setName(name);
    }

    public void openBluetooth() {
        if (!this.getBluetoothAdapter().isEnabled()) {
            Intent intent = new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE");
            intent.putExtra("android.bluetooth.adapter.extra.DISCOVERABLE_DURATION", 300);
            context.startActivity(intent);
        }

    }

    public void closeBluetooth() {
        if (this.getBluetoothAdapter().isEnabled()) {
            this.getBluetoothAdapter().disable();
        }

    }

    public void openBluetoothServer() {
        if (this.bluetoothSocket != null) {
            this.listenerCallback = false;
            this.close();
            this.listenerCallback = true;
        }

        if (!this.serverThreadSwitch) {
            this.serverThreadSwitch = true;
            this.serverThread = new BluetoothUtils.ServerThread(null);
            this.serverThread.start();
            this.mType = BluetoothUtils.CONNECION.SERVER;
        }

    }

    public void closeBluetoothServer() {
        this.close();
    }

    public List<BluetoothDevice> getPairConnList() {
        Set<BluetoothDevice> devices = this.getBluetoothAdapter().getBondedDevices();
        List<BluetoothDevice> deviceList = new ArrayList();

        for (int i = 0; i < devices.size(); ++i) {
            BluetoothDevice device = (BluetoothDevice) devices.iterator().next();
            deviceList.add(device);
        }

        return deviceList;
    }

    public void startDiscovery() {
        if (this.scanBluetooth == null) {
            this.scanBluetooth = new ArrayList();
        }

        this.scanBluetooth.clear();
        if (this.getBluetoothAdapter().isDiscovering()) {
            this.cancelDiscovery();
        }

        this.getBluetoothAdapter().startDiscovery();
    }

    public void addScanDevice(BluetoothDevice bluetoothDevice) {
        if (!this.scanBluetooth.contains(bluetoothDevice)) {
            this.scanBluetooth.add(bluetoothDevice);
        }

    }

    public List<BluetoothDevice> getScanBluetoothList() {
        if (this.scanBluetooth == null) {
            this.scanBluetooth = new ArrayList();
        }

        return this.scanBluetooth;
    }

    public void clearScanBluetoothList() {
        if (this.scanBluetooth != null) {
            this.scanBluetooth.clear();
        }

    }

    public void cancelDiscovery() {
        this.getBluetoothAdapter().cancelDiscovery();
    }

    public boolean createBond(BluetoothDevice bluetoothDevice) {
        try {
            Method creMethod = BluetoothDevice.class.getMethod("createBond");
            return (Boolean) creMethod.invoke(bluetoothDevice);
        } catch (Exception var3) {
            return false;
        }
    }

    public boolean cancelBond(BluetoothDevice bluetoothDevice) {
        try {
            Method creMethod = BluetoothDevice.class.getMethod("removeBond");
            return (Boolean) creMethod.invoke(bluetoothDevice);
        } catch (Exception var3) {
            return false;
        }
    }

    public void connection(BluetoothDevice bluetoothDevice) {
        this.clientBluetoothDevice = bluetoothDevice;
        if (this.bluetoothSocket != null) {
            this.listenerCallback = false;
            this.close();
            this.listenerCallback = true;
        }

        (new Thread() {
            public void run() {
                try {
                    BluetoothUtils.this.bluetoothSocket = BluetoothUtils.this.clientBluetoothDevice.createRfcommSocketToServiceRecord(BluetoothUtils.this.MY_UUID);
                    BluetoothUtils.this.bluetoothSocket.connect();
                    BluetoothUtils.this.blueOutputStream = BluetoothUtils.this.bluetoothSocket.getOutputStream();
                    BluetoothUtils.this.blueInputStream = BluetoothUtils.this.bluetoothSocket.getInputStream();
                    BluetoothUtils.this.mType = BluetoothUtils.CONNECION.CLIENT;
                    BluetoothUtils.this.sendMessage(1, (Object) null, 0, 0);
                    BluetoothUtils.this.readThread = BluetoothUtils.this.new ReadThread(null);
                    BluetoothUtils.this.readThread.start();
                } catch (IOException var2) {
                    BluetoothUtils.this.sendMessage(2, var2.getMessage(), 0, 0);
                }

            }
        }).start();
    }

    public void close() {
        try {
            if (this.bluetoothServerSocket == null && (!this.getBluetoothAdapter().isEnabled() || this.bluetoothSocket == null || !this.bluetoothSocket.isConnected())) {
                this.sendMessage(5, "蓝牙连接没有打开", 0, 0);
                return;
            }

            this.clearScanBluetoothList();
            if (this.blueOutputStream != null) {
                this.blueOutputStream.flush();
                this.blueOutputStream.close();
                this.blueOutputStream = null;
            }

            if (this.blueInputStream != null) {
                this.blueInputStream.close();
                this.blueInputStream = null;
            }

            if (this.readThread != null) {
                this.readThreadSwitch = false;
                this.readThread.interrupt();
                this.readThread = null;
            }

            if (this.mType == BluetoothUtils.CONNECION.CLIENT) {
                this.clientBluetoothDevice = null;
                if (this.bluetoothSocket != null) {
                    this.bluetoothSocket.close();
                }

                this.bluetoothSocket = null;
            } else if (this.mType == BluetoothUtils.CONNECION.SERVER) {
                if (this.serverThread != null) {
                    this.serverThreadSwitch = false;
                    this.serverThread.interrupt();
                    this.serverThread = null;
                }

                if (this.bluetoothServerSocket != null) {
                    this.bluetoothServerSocket.close();
                }

                this.bluetoothServerSocket = null;
            }

            this.sendMessage(4, "蓝牙连接关闭成功", 0, 0);
        } catch (Exception var2) {
            this.sendMessage(5, "蓝牙连接关闭失败", 0, 0);
            this.bluetoothSocket = null;
        }

    }

    public interface BluetoothConnListener {
        void serverOpen();

        void serverClose();

        void connSuccess();

        void connError(String var1);

        void connClose(boolean var1, String var2);

        void onReceive(byte[] var1);

        void onReceiveError(String var1);
    }

    private class ReadThread extends Thread {
        private ReadThread(Object o) {
        }

        public void run() {
            BluetoothUtils.this.readThreadSwitch = true;
            Bundle bundle = new Bundle();

            try {
                while (BluetoothUtils.this.readThreadSwitch) {
                    byte[] buf = new byte[1024];
                    boolean var3 = true;

                    while (BluetoothUtils.this.blueInputStream.read(buf) != -1) {
                        bundle.putByteArray("data", buf);
                        BluetoothUtils.this.sendBundleMessage(300, (Object) null, bundle);
                    }
                }
            } catch (Exception var4) {
                BluetoothUtils.this.sendMessage(301, var4.getMessage(), 0, 0);
            }

        }
    }

    private class ServerThread extends Thread {
        private ServerThread(Object o) {
        }

        public void run() {
            while (BluetoothUtils.this.serverThreadSwitch) {
                try {
                    BluetoothUtils.this.bluetoothServerSocket = BluetoothUtils.this.getBluetoothAdapter().listenUsingRfcommWithServiceRecord(BluetoothUtils.this.getBluetoothAdapter().getName(), BluetoothUtils.this.MY_UUID);
                    LogUtils.d("server", new Object[]{"wait cilent connect..."});
                    BluetoothUtils.this.sendMessage(200, (Object) null, 0, 0);
                    BluetoothUtils.this.bluetoothSocket = BluetoothUtils.this.bluetoothServerSocket.accept();
                    BluetoothUtils.this.blueInputStream = BluetoothUtils.this.bluetoothSocket.getInputStream();
                    BluetoothUtils.this.blueOutputStream = BluetoothUtils.this.bluetoothSocket.getOutputStream();
                    LogUtils.d("server", new Object[]{"accept success !"});
                    BluetoothUtils.this.readThread = BluetoothUtils.this.new ReadThread(null);
                    BluetoothUtils.this.readThread.start();
                    BluetoothUtils.this.sendMessage(201, (Object) null, 0, 0);
                } catch (IOException var2) {
                    BluetoothUtils.this.sendMessage(203, var2.getMessage(), 0, 0);
                }
            }

            LogUtils.d("server", new Object[]{"server close!"});
            BluetoothUtils.this.sendMessage(204, (Object) null, 0, 0);
        }
    }

    public static enum CONNECION {
        NONE,
        CLIENT,
        SERVER;

        private CONNECION() {
        }
    }
}